<script setup lang="ts">
defineOptions({
  name: "Decoration"
});

import { ref, onMounted, reactive, computed, nextTick } from "vue";
import { getChargeStandardList } from "@/api/chargeStandard";
import {
  ElButton,
  ElInput,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElTag,
  ElMessage,
  ElMessageBox,
  ElDialog,
  ElSelect,
  ElOption,
  ElForm,
  ElFormItem,
  ElDatePicker,
  ElLoading,
  ElCol,
  ElRow
} from "element-plus";
import {
  getDecorationManagementList,
  getDecorationManagementById,
  addDecorationManagement,
  updateDecorationManagement,
  deleteDecorationManagement,
  approveDecoration,
  inspectDecoration,
  findDecorationByKeyword,
  DecorationQueryDto
} from "@/api/decorationManagement";
import { findAllCells } from "@/api/cell";
import type {
  DecorationManagementListVo,
  DecorationManagementQueryDto,
  DecorationDetailDto
} from "@/api/decorationManagement";
import type { Cell } from "@/api/cell";

// 搜索相关
const searchKeyword = ref("");

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);
const loading = ref(false);
const decorations = ref<any[]>([]);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("新增装修申请");
const isEdit = ref(false);
const isDetail = ref(false);
const formRef = ref();

// 小区数据
interface CommunityOption {
  label: string;
  value: string;
}
const communities = ref<CommunityOption[]>([{ label: "全部", value: "" }]);

// 表单数据
const formData = reactive({
  id: undefined,
  cellId: "",
  cellName: "",
  houseNumber: "",
  decorationCompany: "",
  applicant: "",
  applicationDate: "",
  decorationDeposit: 0,
  status: "待审核",
  decorationContent: "",
  approver: "",
  applicantPhone: "",
  constructionUnit: "",
  responsiblePerson: "",
  responsiblePhone: "",
  constructionStartTime: "",
  constructionEndTime: "",
  decorationDrawingsUrl: "",
  remark: "",
  totalFee: 0,
  paymentStatus: 0,
  rejectReason: "",
  chargeStandards: [] // 存储选中的收费标准项目
});

// 表单校验规则
const rules = {
  cellId: [{ required: true, message: "请选择小区", trigger: "change" }],
  applicant: [{ required: true, message: "请输入申请人", trigger: "blur" }],
  applicantPhone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur"
    }
  ]
};

// 状态选项
const statusOptions = [
  { label: "待审核", value: "待审核" },
  { label: "已拒绝", value: "已拒绝" },
  { label: "待装修", value: "待装修" },
  { label: "装修中", value: "装修中" },
  { label: "已验收", value: "已验收" }
];

// 小区选择变化处理
const handleCellChange = (cellId: string) => {
  const cellOption = communities.value.find(item => item.value === cellId);
  if (cellOption) {
    formData.cellName = cellOption.label;
  }
};

// 加载小区数据
const loadCommunities = async () => {
  try {
    const response = await findAllCells();
    if (response.code === 0 || response.code === 200) {
      const cellOptions = (response.data || []).map((cell: Cell) => ({
        label: cell.name,
        value: cell.id.toString()
      }));
      communities.value = [{ label: "全部", value: "" }, ...cellOptions];
    }
  } catch (error) {
    console.error("获取小区数据失败:", error);
  }
};

// 加载装修数据
const loadDecorationData = async () => {
  loading.value = true;
  try {
    if (searchKeyword.value) {
      // 使用关键词查询接口
      const keywordQueryDto: DecorationQueryDto = {
        keyword: searchKeyword.value
      };
      const response = await findDecorationByKeyword(keywordQueryDto);
      
      // 将结果适配为分页格式
      if (response?.code === 200) {
        // 关键词查询返回的是直接的数组
        decorations.value = response?.data || [];
        totalCount.value = decorations.value.length;
      } else {
        ElMessage.error(response?.message || "关键词查询失败");
      }
    } else {
      // 空关键词时使用原有的分页查询接口
      const queryDto: DecorationManagementQueryDto = {
        page: currentPage.value,
        limit: pageSize.value
      };
      const response = await getDecorationManagementList(queryDto);
      if (response?.code === 0 || response?.code === 200) {
        decorations.value = response?.data?.list || [];
        totalCount.value = response?.data?.total || 0;
      } else {
        ElMessage.error(response?.message || "获取装修数据失败");
      }
    }
  } catch (error) {
    console.error("获取装修数据失败:", error);
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1;
  loadDecorationData();
};

// 重置搜索
const handleReset = () => {
  searchKeyword.value = "";
  // 不需要重置联系电话和小区ID，因为它们不再用于搜索
  currentPage.value = 1;
  loadDecorationData();
};

// 分页变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadDecorationData();
};

const handlePageChange = (current: number) => {
  currentPage.value = current;
  loadDecorationData();
};

// 添加装修
const handleAdd = () => {
  isDetail.value = false;
  dialogTitle.value = "新增装修申请";
  isEdit.value = false;
  resetForm();
  // 确保cellId为空字符串，避免默认值问题
  formData.cellId = "";
  dialogVisible.value = true;
};

// 编辑装修 - 参考项目中其他组件的标准实现
const handleEdit = async (row: DecorationManagementListVo) => {
  isDetail.value = false;
  dialogTitle.value = "编辑装修申请";
  resetForm();
  // 在resetForm后重新设置isEdit状态
  isEdit.value = true;

  try {
    // 先使用表格行数据进行快速回显，确保用户体验
    formData.id = row.id;
    // 确保cellId是字符串类型，避免数字ID问题
    formData.cellId = String(row.cellId || "");
    // 根据cellId找到对应的小区名称
    const cellOption = communities.value.find(
      item => item.value === formData.cellId
    );
    formData.cellName = cellOption ? cellOption.label : row.cellName || "";
    formData.houseNumber = row.houseNumber;
    formData.decorationCompany = row.decorationCompany;
    formData.applicant = row.applicant;
    // 保持与formData定义的类型一致，不转换为Date对象
    formData.applicationDate = row.applicationDate || "";
    formData.decorationDeposit = row.decorationDeposit || 0;
    formData.status = row.status;
    formData.decorationContent = row.decorationContent;
    formData.approver = row.approver || "";
    formData.applicantPhone = row.applicantPhone;
    formData.constructionUnit = row.constructionUnit;
    formData.responsiblePerson = row.responsiblePerson;
    formData.responsiblePhone = row.responsiblePhone;
    // 保持与formData定义的类型一致，不转换为Date对象
    formData.constructionStartTime = row.constructionStartTime || "";
    formData.constructionEndTime = row.constructionEndTime || "";
    formData.decorationDrawingsUrl = row.decorationDrawingsUrl;
    formData.remark = row.remark;
    formData.totalFee = row.totalFee || 0;
    formData.paymentStatus = row.paymentStatus || 0;
    formData.rejectReason = row.rejectReason;

    // 立即显示弹窗，不等待详情加载完成
    dialogVisible.value = true;

    // 同时异步请求最新数据以确保数据准确性
    try {
      const response = await getDecorationManagementById(row.id);
      if ((response.code === 0 || response.code === 200) && response.data) {
        const data = response.data;
        // 确保decorationData始终是DecorationManagementListVo类型
        const decorationData = data.decorationManagement;
        if (decorationData) {
          // 更新表单数据，保持类型一致
          formData.id = decorationData.id;
          // 确保cellId是字符串类型，避免数字ID问题
          formData.cellId = String(decorationData.cellId || "");
          // 根据cellId找到对应的小区名称
          const cellOption = communities.value.find(
            item => item.value === formData.cellId
          );
          formData.cellName = cellOption
            ? cellOption.label
            : decorationData.cellName || "";
          formData.houseNumber = decorationData.houseNumber;
          formData.decorationCompany = decorationData.decorationCompany;
          formData.applicant = decorationData.applicant;
          formData.applicationDate = decorationData.applicationDate || "";
          formData.decorationDeposit = decorationData.decorationDeposit || 0;
          formData.status = decorationData.status;
          formData.decorationContent = decorationData.decorationContent;
          formData.approver = decorationData.approver || "";
          formData.applicantPhone = decorationData.applicantPhone;
          formData.constructionUnit = decorationData.constructionUnit;
          formData.responsiblePerson = decorationData.responsiblePerson;
          formData.responsiblePhone = decorationData.responsiblePhone;
          formData.constructionStartTime =
            decorationData.constructionStartTime || "";
          formData.constructionEndTime =
            decorationData.constructionEndTime || "";
          formData.decorationDrawingsUrl = decorationData.decorationDrawingsUrl;
          formData.remark = decorationData.remark;
          formData.totalFee = decorationData.totalFee || 0;
          formData.paymentStatus = decorationData.paymentStatus || 0;
          formData.rejectReason = decorationData.rejectReason;
        }
      }
    } catch (detailError) {
      console.log("异步加载最新数据失败，但不影响编辑操作", detailError);
      // 静默失败，不影响用户体验
    }
  } catch (error) {
    console.error("编辑装修申请失败:", error);
    ElMessage.error("编辑装修申请失败");
  }
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(formData, {
    id: undefined,
    cellId: "",
    cellName: "",
    houseNumber: "",
    decorationCompany: "",
    applicant: "",
    applicationDate: "",
    decorationDeposit: 0,
    status: "待审核",
    decorationContent: "",
    approver: "",
    applicantPhone: "",
    constructionUnit: "",
    responsiblePerson: "",
    responsiblePhone: "",
    constructionStartTime: "",
    constructionEndTime: "",
    decorationDrawingsUrl: "",
    remark: "",
    totalFee: 0,
    paymentStatus: 0,
    rejectReason: "",
    chargeStandards: []
  });
  isEdit.value = false;
  isDetail.value = false;
};

// 保存装修信息
const handleSave = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    ElLoading.service({
      lock: true,
      text: "正在保存...",
      background: "rgba(0, 0, 0, 0.7)"
    });

    // 格式化所有日期字段为正确的字符串格式
    const formatDateField = (date: any) => {
      if (!date) return "";

      // 创建日期对象
      const dateObj =
        typeof date === "string" ? new Date(date) : new Date(date);

      // 检查日期是否有效
      if (isNaN(dateObj.getTime())) return "";

      // 格式化为后端可接受的日期时间格式: YYYY-MM-DD HH:mm:ss
      // 如果输入是简单的YYYY-MM-DD格式，添加时间部分
      const year = dateObj.getFullYear();
      const month = String(dateObj.getMonth() + 1).padStart(2, "0");
      const day = String(dateObj.getDate()).padStart(2, "0");
      const hours = String(dateObj.getHours()).padStart(2, "0");
      const minutes = String(dateObj.getMinutes()).padStart(2, "0");
      const seconds = String(dateObj.getSeconds()).padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    const submitData = {
      ...formData,
      applicationDate: formatDateField(formData.applicationDate),
      constructionStartTime: formatDateField(formData.constructionStartTime),
      constructionEndTime: formatDateField(formData.constructionEndTime)
    };

    let response;
    if (isEdit.value || isDetail.value) {
      response = await updateDecorationManagement(submitData);
    } else {
      response = await addDecorationManagement(submitData);
    }

    if (response.code === 0 || response.code === 200) {
      ElMessage.success(
        isEdit.value || isDetail.value ? "更新成功" : "添加成功"
      );
      dialogVisible.value = false;
      await loadDecorationData();
    } else {
      ElMessage.error(
        response.message ||
          (isEdit.value || isDetail.value ? "更新失败" : "添加失败")
      );
    }
  } catch (error: any) {
    console.error("保存装修信息失败:", error);
    if (!error?.message?.includes("cancel")) {
      ElMessage.error("保存失败");
    }
  } finally {
    ElLoading.service().close();
  }
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
  resetForm();
};

// 收费标准弹窗相关
const chargeStandardsDialogVisible = ref(false);
const chargeStandardsList = ref<any[]>([]);
const chargeStandardsLoading = ref(false);
const selectedChargeStandards = ref<any[]>([]);
const savedChargeStandards = ref<{ id: string; quantity: number }[]>([]); // 保存选中的收费标准和数量
const tableRef = ref<InstanceType<typeof ElTable>>(); // 表格引用

// 显示收费标准弹窗
const showChargeStandards = async () => {
  await loadChargeStandards();

  // 先打开弹窗
  chargeStandardsDialogVisible.value = true;

  // 使用nextTick确保DOM更新后再恢复选中状态
  nextTick(() => {
    if (
      savedChargeStandards.value.length > 0 &&
      tableRef.value &&
      chargeStandardsList.value.length > 0
    ) {
      console.log(
        "恢复选中状态，保存的项目数量:",
        savedChargeStandards.value.length
      );

      // 清除之前的选择
      tableRef.value.clearSelection();

      // 遍历保存的项目，设置选中状态
      savedChargeStandards.value.forEach(savedItem => {
        const matchingItem = chargeStandardsList.value.find(
          item => item.id === savedItem.id
        );
        if (matchingItem && tableRef.value) {
          console.log("选中项目:", matchingItem.name);
          tableRef.value.toggleRowSelection(matchingItem, true);
        }
      });
    } else {
      // 如果没有保存的选中项，清除选择
      if (tableRef.value) {
        tableRef.value.clearSelection();
      }
      selectedChargeStandards.value = [];
    }
  });
};

// 加载收费标准列表
const loadChargeStandards = async () => {
  chargeStandardsLoading.value = true;
  try {
    const response = await getChargeStandardList({
      page: 1,
      limit: 100, // 获取足够多的数据用于选择
      name: "" // 空字符串表示查询所有
    });
    if (response.code === 0 || response.code === 200) {
      // 获取所有收费标准数据
      const standards = (response.data?.list || []).map((item: any) => ({
        ...item,
        quantity: 1 // 默认数量为1
      }));

      // 如果有保存的收费标准，恢复数量和选中状态
      if (savedChargeStandards.value.length > 0) {
        standards.forEach(standard => {
          const savedItem = savedChargeStandards.value.find(
            item => item.id === standard.id
          );
          if (savedItem) {
            standard.quantity = savedItem.quantity; // 恢复保存的数量
          }
        });
      }

      chargeStandardsList.value = standards;
    } else {
      ElMessage.error(response.message || "获取收费标准失败");
    }
  } catch (error) {
    console.error("获取收费标准失败:", error);
    ElMessage.error("获取收费标准失败");
  } finally {
    chargeStandardsLoading.value = false;
  }
};

// 确认选择收费标准
const confirmChargeStandards = () => {
  console.log("选中项:", selectedChargeStandards.value); // 调试信息
  console.log("选中数量:", selectedChargeStandards.value.length);
  if (selectedChargeStandards.value.length === 0) {
    ElMessage.warning("请至少选择一项收费标准");
    return;
  }

  // 保存选中的项目及其数量
  savedChargeStandards.value = selectedChargeStandards.value.map(item => ({
    id: item.id,
    quantity: item.quantity || 1
  }));

  // 同时保存到formData中，用于提交给后端
  formData.chargeStandards = savedChargeStandards.value;
  console.log("formData.chargeStandards已更新:", formData.chargeStandards);

  // 计算总费用
  const totalFee = selectedChargeStandards.value.reduce((sum, item) => {
    const quantity = item.quantity || 1;
    const price = parseFloat(item.price) || 0;
    return sum + price * quantity;
  }, 0);

  // 更新表单总费用
  formData.totalFee = totalFee;

  ElMessage.success(
    `已选择 ${selectedChargeStandards.value.length} 项收费标准，总计：${totalFee} 元`
  );
  chargeStandardsDialogVisible.value = false;
};

// 处理选中变化
const handleSelectionChange = (selection: any[]) => {
  console.log("选择变化:", selection.length, "项");
  selectedChargeStandards.value = selection;
};

// 关闭收费标准弹窗
const closeChargeStandardsDialog = () => {
  chargeStandardsDialogVisible.value = false;
  selectedChargeStandards.value = [];
};

// 删除装修
const handleDelete = async (row: DecorationManagementListVo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除装修申请「${row.decorationContent}」吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const response = await deleteDecorationManagement(row.id!);
    if (response.code === 0 || response.code === 200) {
      ElMessage.success("删除成功");
      await loadDecorationData();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error: any) {
    if (!error?.message?.includes("cancel")) {
      console.error("删除装修申请失败:", error);
    }
  }
};

// 查看详情
const handleDetail = async (row: DecorationManagementListVo) => {
  isDetail.value = true;
  dialogTitle.value = "装修申请详情";
  resetForm();
  // 在resetForm后重新设置isDetail状态
  isDetail.value = true;

  // 使用表格行数据进行快速回显
  formData.id = row.id;
  // 确保cellId是字符串类型，避免数字ID问题
  formData.cellId = String(row.cellId || "");
  // 根据cellId找到对应的小区名称
  const cellOption = communities.value.find(item => item.value === formData.cellId);
  formData.cellName = cellOption ? cellOption.label : row.cellName || "";
  formData.houseNumber = row.houseNumber;
  formData.decorationCompany = row.decorationCompany;
  formData.applicant = row.applicant;
  formData.applicationDate = row.applicationDate || "";
  formData.decorationDeposit = row.decorationDeposit || 0;
  formData.status = row.status;
  formData.decorationContent = row.decorationContent;
  formData.approver = row.approver || "";
  formData.applicantPhone = row.applicantPhone;
  formData.constructionUnit = row.constructionUnit;
  formData.responsiblePerson = row.responsiblePerson;
  formData.responsiblePhone = row.responsiblePhone;
  formData.constructionStartTime = row.constructionStartTime || "";
  formData.constructionEndTime = row.constructionEndTime || "";
  formData.decorationDrawingsUrl = row.decorationDrawingsUrl;
  formData.remark = row.remark;
  formData.totalFee = row.totalFee || 0;
  formData.paymentStatus = row.paymentStatus || 0;
  formData.rejectReason = row.rejectReason;

  // 显示弹窗
  dialogVisible.value = true;
};

// 审核装修
const handleApprove = async (row: DecorationManagementListVo) => {
  try {
    await ElMessageBox.confirm(`确定要审核此装修申请吗？`, "确认审核", {
      confirmButtonText: "同意",
      cancelButtonText: "拒绝",
      type: "warning",
      distinguishCancelAndClose: true
    }).then(
      async () => {
        // 同意审核
        ElLoading.service({
          lock: true,
          text: "正在审核...",
          background: "rgba(0, 0, 0, 0.7)"
        });
        try {
          const response = await approveDecoration(row.id!, "待装修", "管理员");
          if (response.code === 0 || response.code === 200) {
            ElMessage.success("审核通过");
            await loadDecorationData();
          } else {
            ElMessage.error(response.message || "审核失败");
          }
        } catch (error) {
          console.error("审核装修失败:", error);
          ElMessage.error("审核失败");
        } finally {
          ElLoading.service().close();
        }
      },
      async () => {
        // 拒绝审核
        await ElMessageBox.prompt("请输入拒绝原因", "拒绝审核", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputType: "textarea",
          inputPattern: /^\S+/,
          inputErrorMessage: "拒绝原因不能为空"
        }).then(async ({ value }) => {
          ElLoading.service({
            lock: true,
            text: "正在处理...",
            background: "rgba(0, 0, 0, 0.7)"
          });
          try {
            // 这里可以调用拒绝审核的API
            // 暂时通过更新状态来实现
            const updateData = {
              ...row,
              status: "已拒绝",
              rejectReason: value
            };
            const response = await updateDecorationManagement(updateData);
            if (response.code === 0 || response.code === 200) {
              ElMessage.success("已拒绝");
              await loadDecorationData();
            } else {
              ElMessage.error(response.message || "操作失败");
            }
          } catch (error) {
            console.error("拒绝审核失败:", error);
            ElMessage.error("操作失败");
          } finally {
            ElLoading.service().close();
          }
        });
      }
    );
  } catch (error: any) {
    if (!error?.message?.includes("cancel")) {
      console.error("审核装修失败:", error);
    }
  }
};

// 验收装修
const handleInspect = async (row: DecorationManagementListVo) => {
  try {
    // 分步收集验收信息
    // 第一步：收集验收人姓名
    const { value: inspector } = await ElMessageBox.prompt(
      "请输入验收人姓名",
      "确认验收",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^\S+$/,
        inputErrorMessage: "验收人不能为空"
      }
    );

    // 第二步：选择验收结果
    const { value: inspectionResult } = await ElMessageBox.confirm(
      "请选择验收结果",
      "验收结果",
      {
        confirmButtonText: "通过",
        cancelButtonText: "不通过",
        type: "warning",
        distinguishCancelAndClose: true
      }
    ).then(
      () => ({ value: "通过" }),
      () => ({ value: "不通过" })
    );

    // 第三步：收集验收备注（可选）
    const { value: inspectionNotes } = await ElMessageBox.prompt(
      "请输入验收备注（可选）",
      "验收备注",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "textarea",
        inputPlaceholder: "请输入验收备注信息"
      }
    );

    // 第四步：收集验收照片URL（可选）
    const { value: inspectionPhotosUrl } = await ElMessageBox.prompt(
      "请输入验收照片URL（可选，多个用逗号分隔）",
      "验收照片",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPlaceholder: "多个照片URL用逗号分隔"
      }
    );

    // 提交验收
    ElLoading.service({
      lock: true,
      text: "正在提交验收...",
      background: "rgba(0, 0, 0, 0.7)"
    });
    try {
      // 调用验收API，传递所有参数
      const response = await inspectDecoration(
        row.id!,
        inspector,
        inspectionResult,
        inspectionNotes || "",
        inspectionPhotosUrl || undefined
      );
      if (response.code === 0 || response.code === 200) {
        ElMessage.success("验收成功");
        await loadDecorationData();
      } else {
        ElMessage.error(response.message || "验收失败");
      }
    } catch (error) {
      console.error("验收装修失败:", error);
      ElMessage.error("验收失败");
    } finally {
      ElLoading.service().close();
    }
  } catch (error: any) {
    if (!error?.message?.includes("cancel")) {
      console.error("验收装修失败:", error);
    }
  }
};

// 状态标签样式
const getStatusTagType = (status: string) => {
  switch (status) {
    case "待审核":
      return "warning";
    case "已拒绝":
      return "danger";
    case "待装修":
      return "info";
    case "装修中":
      return "primary";
    case "已验收":
      return "success";
    default:
      return "info";
  }
};

// 格式化日期
const formatDate = (date: string | Date | undefined) => {
  if (!date) return "--";
  const d = new Date(date);
  return d
    .toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit"
    })
    .replace(/\//g, "-");
};

// 查找小区名称
const findCellNameById = (cellId: string) => {
  if (!cellId) return "-";
  const cellOption = communities.value.find(item => item.value === cellId);
  return cellOption ? cellOption.label : "-";
};

// 组件挂载时加载数据
onMounted(async () => {
  await loadCommunities();
  await loadDecorationData();
});
</script>

<template>
  <div class="decoration-container">
    <div class="header-bar">
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入姓名/房号/手机号搜索"
          style="width: 300px; margin-right: 10px"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button
              type="primary"
              @click="handleSearch"
            >搜索</el-button>
          </template>
        </el-input>
        <el-button type="primary" @click="handleAdd">+ 装修申请</el-button>
      </div>
    </div>

    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="decorations"
        style="width: 100%"
        border
      >
        <el-table-column label="小区" min-width="100">
          <template #default="{ row }">
            <span>{{
              row.cellName || findCellNameById(row.cellId) || "-"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="houseNumber" label="房号" min-width="100" />
        <el-table-column
          prop="decorationCompany"
          label="装修公司"
          min-width="120"
        />
        <el-table-column prop="applicant" label="申请人" min-width="100" />
        <el-table-column label="申请日期" min-width="120">
          <template #default="{ row }">
            {{ formatDate(row.applicationDate) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="decorationDeposit"
          label="装修押金(元)"
          min-width="120"
        >
          <template #default="{ row }">
            {{ row.decorationDeposit || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{
              row.status
            }}</el-tag>
            <div
              v-if="row.status === '已拒绝' && row.rejectReason"
              class="reject-reason"
            >
              <span class="reject-label">拒绝原因：</span>
              <span>{{ row.rejectReason }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="decorationContent"
          label="装修内容"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column prop="approver" label="审批人" min-width="100">
          <template #default="{ row }">
            {{ row.approver || "--" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === '待审核'"
              type="success"
              link
              size="small"
              @click="handleApprove(row)"
            >
              审核
            </el-button>
            <el-button
              v-if="row.status === '装修中' || row.status === '待装修'"
              type="primary"
              link
              size="small"
              @click="handleInspect(row)"
            >
              验收
            </el-button>
            <el-button type="info" link size="small" @click="handleDetail(row)">
              详情
            </el-button>
            <el-button
              type="warning"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="prev, pager, next, jumper, sizes, total"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 装修申请对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :before-close="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        :disabled="isDetail"
        label-width="120px"
        class="decoration-form"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="小区" prop="cellId">
              <template v-if="isDetail">
                <span>{{ formData.cellName || findCellNameById(formData.cellId) || '-' }}</span>
              </template>
              <template v-else>
                <el-select
                  v-model="formData.cellId"
                  placeholder="请选择小区"
                  @change="handleCellChange"
                  filterable
                >
                  <el-option
                    v-for="item in communities.filter(item => item.value !== '')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房间号" prop="houseNumber">
              <el-input
                v-model="formData.houseNumber"
                placeholder="请输入房间号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="装修公司" prop="decorationCompany">
              <el-input
                v-model="formData.decorationCompany"
                placeholder="请输入装修公司"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人" prop="applicant">
              <el-input
                v-model="formData.applicant"
                placeholder="请输入申请人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="applicantPhone">
              <el-input
                v-model="formData.applicantPhone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请日期" prop="applicationDate">
              <el-date-picker
                v-model="formData.applicationDate"
                type="date"
                placeholder="请选择申请日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="装修押金" prop="decorationDeposit">
              <el-input
                v-model.number="formData.decorationDeposit"
                placeholder="请输入装修押金"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <div style="display: flex; gap: 10px; align-items: center">
                <el-select
                  v-model="formData.status"
                  placeholder="请选择状态"
                  style="width: 120px"
                >
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="!isEdit && !isDetail && item.value === '已拒绝'"
                  />
                </el-select>
                <el-button
                  type="primary"
                  size="small"
                  @click="showChargeStandards"
                  :disabled="isDetail"
                >
                  收费标准
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="装修内容" prop="decorationContent">
              <el-input
                v-model="formData.decorationContent"
                type="textarea"
                :rows="3"
                placeholder="请输入装修内容"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="isEdit || isDetail" :span="24">
            <el-form-item label="拒绝原因" prop="rejectReason">
              <el-input
                v-model="formData.rejectReason"
                type="textarea"
                :rows="3"
                placeholder="请输入拒绝原因"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button v-if="!isDetail" type="primary" @click="handleSave"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 收费标准选择弹窗 -->
    <el-dialog
      v-model="chargeStandardsDialogVisible"
      title="选择收费项目"
      width="800px"
      :before-close="closeChargeStandardsDialog"
      :close-on-click-modal="false"
    >
      <el-table
        ref="tableRef"
        v-loading="chargeStandardsLoading"
        :data="chargeStandardsList"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="chargeitemName"
          label="收费项目"
          min-width="120"
        />
        <el-table-column prop="name" label="收费标准名称" min-width="150" />
        <el-table-column
          prop="chargetypeName"
          label="项目类别"
          min-width="100"
        />
        <el-table-column prop="priceStr" label="金额计算方式" min-width="120" />
        <el-table-column prop="price" label="单价" min-width="80" />
        <el-table-column label="数量" min-width="100">
          <template #default="{ row }">
            <el-input
              v-model.number="row.quantity"
              placeholder="请输入数量"
              style="width: 120px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="计量方式" min-width="100" />
      </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeChargeStandardsDialog">取消</el-button>
          <el-button type="primary" @click="confirmChargeStandards"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.decoration-container {
  padding: 20px;
}

.header-bar {
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  align-items: center;
}

.table-container {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.decoration-form {
  max-height: 60vh;
  overflow-y: auto;
}

.reject-reason {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.reject-label {
  color: #606266;
}
</style>
